package com.thread.jucTest;

import org.junit.Test;

/**
 * @program: leetcode
 * @description:
 * @author: wangzhihua
 * @date: 2024-06-22
 */
public class VolatileTest {

	class AObject extends Thread {
//		boolean flag = false;
		volatile boolean flag = false;
		@Override
		public void run() {
			while (!flag) {

			}
			System.out.println("flag = true");
		}
	}

	@Test
	public void test1() {
		AObject aObject = new AObject();
		aObject.start();
		synchronized (aObject) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(aObject.flag);
		}
	}

	@Test
	public void test2() {
		AObject aObject = new AObject();
		aObject.setDaemon(true);
		aObject.start();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		synchronized (aObject) {
			aObject.flag = true;
		}
	}

	@Test
	public void test3() {
		AObject aObject = new AObject();
		aObject.setDaemon(true);
		aObject.start();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		aObject.flag = true;
	}

}
